extends Node


const Directions = [
	Vector2.LEFT, Vector2.RIGHT, Vector2.UP, Vector2.DOWN
]


##  最大x轴位置
export var max_x : int = 2
export var height : int = 3
export (float, 0.0, 1.0) var ratio : float = 0.4
export var min_generate_count : int = 25


var current_pos : Vector2 = Vector2.ZERO
var default = []
var pos_list : Dictionary = {}


func get_map_pos_list() -> Array:
	return pos_list.keys()

##  到达最小数量
func is_min_count():
	return pos_list.size() >= min_generate_count + default.size()

func get_next_dir(pos: Vector2) -> Vector2:
	# 四周方向的位置
	var p = {
		left = pos + Vector2.LEFT,
		right = pos + Vector2.RIGHT,
		up = pos + Vector2.UP,
		down = pos + Vector2.DOWN,
	}
	var list = [Vector2.LEFT, Vector2.RIGHT, Vector2.UP, Vector2.DOWN]
	# 如果已经存在则代表已移动到过了，则 erase
	if pos_list.has(p.left) || p.left.x < -max_x:
		list.erase(Vector2.LEFT)
	if pos_list.has(p.right) || p.right.x > max_x:
		list.erase(Vector2.RIGHT)
	if pos_list.has(p.up):
		list.erase(Vector2.UP)
	if pos_list.has(p.down):
		list.erase(Vector2.DOWN)
	
	# 如果没有可移动的方向，则向上下移动
	var dir = Vector2(0,0)
	if list.size() != 0:
		dir = list[randi() % list.size()]
	else:
		dir = [Vector2.DOWN, Vector2.UP][randi() % 2]
	return dir


func _enter_tree():
	start()


func start():
	# 默认位置（中间会先生成两列 height * 2 个数的位置）
	for i in range(height):
		default.push_back(Vector2(0, i))
		default.push_back(Vector2(1, i))
	for p in default:
		pos_list[p] = true
	
#	auto_move(Vector2(0,0))
#	return
	
	# 开始生成，最多生成 10 次
	for i in range(10):
		move_left_and_right()
		# 数量到达最小数量时则跳出循环
		if is_min_count():
			break


## 左右移动
func move_left_and_right():
	for p in default:
		if is_min_count():
			break
		
		current_pos = p
		if randf() < ratio:
			if p.x == 0:	# 左边
				_move_next(Vector2.LEFT)	# 左边移动一下先
				for i in range(max_x-1):
					_move_next(get_next_dir(current_pos))
		
		if randf() < ratio:
			if p.x == 1:	# 右边
				_move_next(Vector2.RIGHT)	# 右边移动一下先
				for i in range(max_x-1):
					_move_next(get_next_dir(current_pos))


##  移动到下一个位置
func _move_next(dir):
	var to = current_pos + dir
	current_pos = to
	pos_list[to] = true


##  自动移动
## 这种生成方式比较分散
func auto_move(start_pos: Vector2):
	current_pos = start_pos
	# 开始生成
	var pos = start_pos
	var last_count = 0
	var repeat_count = 0
	while true:
		if is_min_count():
			break
		pos += get_next_dir(pos)
		pos_list[pos] = true
		if last_count != pos_list.size():
			last_count = pos_list.size()
		else:
			repeat_count += 1
			if repeat_count > 100:
				break
	

